#!/usr/bin/env bash

giturl="https://gitee.com/hornleaf/vsccss/raw/master/code.sh"
shaurl="https://code.visualstudio.com/sha/?build=stable"
url="https://vscode.download.prss.microsoft.com/dbazure/download/stable/%s/vscode_cli_alpine_%s_cli.tar.gz"

if [ ! -z $commit ];then
  sha=$commit
else
  echo "正从 $(awk -F'[/:]' '{print $4}' <<< $shaurl) 获取版本信息..."
shas="$(curl -sL $shaurl)"
  sha=$(grep "version\":.*?," -Po <<< $shas | head -n1 | sed 's/version//' | grep -Eo "[0-9a-f]+")
fi

echo "commit: ${sha:-Null}"
[[ ${sha:-Null} == Null ]] && exit 1
if [ -z $version ];then
  version=$(grep "name\":\"([0-9]{1,2}.){2}[0-9]{1,2}.*?," -Po <<< $shas | head -n1 | grep -Eo "([0-9]{1,2}.){2}[0-9]{1,2}")
fi
echo "version: ${version:-Null}"
[[ ${version:-Null} == Null ]] && exit 1

echo -n "获取架构名称: "

arch=$(uname -m)
case $arch in
  armv7* | armv8l) aarch=armhf;;
  aarch64 | armv8* | arm64 | arm*)aarch=arm64;;
  x86_64 | amd64)aarch=x64;;
  *)exec echo "不支持的架构 $arch"
esac
echo $arch

echo "正在挑选对应架构的 tar.gz 压缩包"

tar=$(printf "$url" $sha $aarch)
tarn=$(basename $tar)

if wget -q --show-progress -O $tarn $tar;then
  echo "$tarn 下载完成"
  code_dir=$HOME/VscodeCLI/bin
  [ ! -d $code_dir ] && mkdir -vp $code_dir
  echo "正在解压..."
  if [ -z $(command -v pv) ];then
    tar -zxvf ./$tarn -C $code_dir
  else
    pv ./$tarn | tar -zxvf - -C $code_dir
  fi

  bin=$code_dir/code.sh
  echo "下载启动脚本 code.sh..."
  wget -q --show-progress -O $bin $giturl &&
  chmod -v 755 $bin &&
  echo "code $version 已接受赋权 (755)" &&
  echo "完成。" &&
  rm -v ./$tarn &&
  bash $bin start &&
  echo "执行命令 bash $bin 以使用管理脚本和查看用法"
else
  echo "压缩包下载失败"
  exit
fi